package com.ruoyi.data.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.data.SignUtil;
import com.ruoyi.data.feign.QikeFeign;
import com.ruoyi.data.vo.QikeUrlRequest;
import com.ruoyi.data.vo.QikeUrlResponse;
import com.ruoyi.data.vo.ResultData;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;

@Service
public class DataQikeService {
  @Resource
  private QikeFeign qikeFeign;
  @Value("${qike.ak}")
  private String authId;
  @Value("${qike.sk}")
  private String secretKey;
  @Value("${qike.code}")
  private String code;
  @Value("${qike.appCode}")
  private String appCode;

  private static final List<String> modules = Arrays.asList("searchHome", "filter", "market", "subscribe", "map", "relation", "batch", "unlockRecord", "myClue", "myExportlog");


  public String getUrl(String moduleName) {
    LoginUser loginUser = SecurityUtils.getLoginUser();
    Assert.notNull(loginUser, "用户信息为空");
    Assert.isTrue(modules.contains(moduleName), "未支持的功能");
    String tenant = loginUser.getTenant();
    QikeUrlRequest request = new QikeUrlRequest(tenant, tenant, code, appCode, loginUser.getUserId().toString(), loginUser.getUsername(), moduleName);
    String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis());
    String reqId = UUID.randomUUID().toString();
    TreeMap<String, String> reqParams = Maps.newTreeMap();
    reqParams.put("authid", authId);
    reqParams.put("timestamp", timestamp);
    reqParams.put("reqid", reqId);
    reqParams.put("data", JSON.toJSONString(request));
    String sign = SignUtil.sign(reqParams, secretKey);
    ResultData<QikeUrlResponse> response = qikeFeign.getUrl(request, authId, timestamp, reqId, sign);
    Assert.isTrue(response.getSuccess(), response.getMsg());
    return response.getData().getFullUrl();
  }


}
